package cmd

import (
	"fmt"
	"os"
	"os/signal"
	"strconv"
	"syscall"
	"time"
)

func signalHandle(runType string, f func()) {
	// 注册信号处理器
	sigCh := make(chan os.Signal, 1)
	signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)

	fmt.Println(runType + " Waiting for signals...")

	select {
	case <-sigCh:
		// 执行清理逻辑，如关闭资源、保存状态等
		f()

		ticker := time.NewTicker(time.Second)
		num := 0
		for i := range ticker.C {
			fmt.Println(i, num)
			num++
			if num == 10 {
				panic("after 10 second")
				return
			}
		}
		fmt.Println("close")

		return
	}
}

func writePid(f string) {
	pid := os.Getpid()
	pidStr := strconv.Itoa(pid)
	os.WriteFile(fmt.Sprintf("./%s_pid.log", f), []byte(pidStr), 0777)
}

func readPid(f string) (pid string, err error) {
	bytes, err := os.ReadFile(fmt.Sprintf("./%s_pid.log", f))
	if err != nil {
		fmt.Println(err)
		return
	}
	pid = string(bytes)
	return
}
